// 日常工作问题记录系统 - 核心逻辑

class WorkLogSystem {
    constructor() {
        // 初始化数据和UI元素
        this.logs = this.loadLogs();
        this.currentLogId = null;
        this.initUI();
        this.initEventListeners();
        this.loadSettings();
        this.renderLogList();
        this.setupAutoSave();
    }

    // 从localStorage加载记录数据
    loadLogs() {
        const logs = localStorage.getItem('workLogs');
        return logs ? JSON.parse(logs) : [];
    }

    // 保存记录数据到localStorage
    saveLogs() {
        localStorage.setItem('workLogs', JSON.stringify(this.logs));
    }

    // 加载设置
    loadSettings() {
        const settings = localStorage.getItem('workLogSettings');
        this.settings = settings ? JSON.parse(settings) : {
            theme: 'light',
            autoSave: true,
            saveInterval: 30
        };
        this.applySettings();
    }

    // 保存设置
    saveSettings() {
        localStorage.setItem('workLogSettings', JSON.stringify(this.settings));
        this.applySettings();
    }

    // 应用设置
    applySettings() {
        // 主题设置
        document.body.className = this.settings.theme;
        
        // 自动保存设置
        this.setupAutoSave();
    }

    // 设置自动保存
    setupAutoSave() {
        if (this.autoSaveTimer) {
            clearInterval(this.autoSaveTimer);
        }
        
        if (this.settings.autoSave) {
            this.autoSaveTimer = setInterval(() => {
                if (this.currentLogId) {
                    this.saveCurrentLog();
                }
            }, this.settings.saveInterval * 1000);
        }
    }

    // 初始化UI元素
    initUI() {
        // 获取所有需要的DOM元素
        this.newLogBtn = document.getElementById('new-log-btn');
        this.saveBtn = document.getElementById('save-btn');
        this.deleteBtn = document.getElementById('delete-btn');
        this.exportBtn = document.getElementById('export-btn');
        this.settingsBtn = document.getElementById('settings-btn');
        this.searchInput = document.getElementById('search-input');
        this.searchBtn = document.getElementById('search-btn');
        this.addTaskBtn = document.getElementById('add-task-btn');
        this.addProblemBtn = document.getElementById('add-problem-btn');
        this.addSolutionBtn = document.getElementById('add-solution-btn');
        
        this.logTitle = document.getElementById('log-title');
        this.logDate = document.getElementById('log-date');
        this.todayTasks = document.getElementById('today-tasks');
        this.problemsContainer = document.getElementById('problems-container');
        this.solutionsContainer = document.getElementById('solutions-container');
        this.learnings = document.getElementById('learnings');
        this.tomorrowPlan = document.getElementById('tomorrow-plan');
        
        this.logList = document.querySelector('.log-list');
        this.templateBtns = document.querySelectorAll('.template-btn');
        
        // 选项卡相关
        this.tabBtns = document.querySelectorAll('.tab-btn');
        this.tabPanes = document.querySelectorAll('.tab-pane');
        
        // 设置模态框相关
        this.settingsModal = document.getElementById('settings-modal');
        this.closeModal = document.querySelector('.close-modal');
        this.saveSettingsBtn = document.getElementById('save-settings-btn');
        this.cancelSettingsBtn = document.getElementById('cancel-settings-btn');
        this.themeSelect = document.getElementById('theme-select');
        this.autoSave = document.getElementById('auto-save');
        this.saveInterval = document.getElementById('save-interval');
        
        // 预览相关
        this.previewTitle = document.getElementById('preview-title');
        this.previewContent = document.getElementById('preview-content');
        
        // 设置当前日期
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        this.logDate.value = formattedDate;
        this.logTitle.value = `${formattedDate} 日常记录`;
    }

    // 初始化事件监听器
    initEventListeners() {
        // 新建记录按钮
        this.newLogBtn.addEventListener('click', () => this.createNewLog());
        
        // 保存记录按钮
        this.saveBtn.addEventListener('click', () => this.saveCurrentLog());
        
        // 删除记录按钮
        this.deleteBtn.addEventListener('click', () => this.deleteCurrentLog());
        
        // 导出数据按钮
        this.exportBtn.addEventListener('click', () => this.exportData());
        
        // 设置按钮
        this.settingsBtn.addEventListener('click', () => this.openSettings());
        
        // 搜索按钮
        this.searchBtn.addEventListener('click', () => this.searchLogs());
        this.searchInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') this.searchLogs();
        });
        
        // 添加任务按钮
        this.addTaskBtn.addEventListener('click', () => {
            const currentValue = this.todayTasks.value;
            const newValue = currentValue ? currentValue + '\n- [ ] 新任务' : '- [ ] 新任务';
            this.todayTasks.value = newValue;
        });
        
        // 添加问题按钮
        this.addProblemBtn.addEventListener('click', () => {
            const problemCount = this.problemsContainer.querySelectorAll('.problem-item').length + 1;
            const problemItem = document.createElement('div');
            problemItem.className = 'problem-item';
            problemItem.innerHTML = `
                <h4>问题${problemCount}：</h4>
                <textarea class="problem-description" rows="2" placeholder="问题描述"></textarea>
                <textarea class="problem-scene" rows="1" placeholder="出现场景"></textarea>
                <textarea class="problem-scope" rows="1" placeholder="影响范围"></textarea>
                <textarea class="problem-methods" rows="1" placeholder="尝试过的方法"></textarea>
                <textarea class="problem-error" rows="1" placeholder="错误信息（如有）"></textarea>
            `;
            this.problemsContainer.appendChild(problemItem);
        });
        
        // 添加解决方案按钮
        this.addSolutionBtn.addEventListener('click', () => {
            const solutionCount = this.solutionsContainer.querySelectorAll('.solution-item').length + 1;
            const solutionItem = document.createElement('div');
            solutionItem.className = 'solution-item';
            solutionItem.innerHTML = `
                <h4>解决方案${solutionCount}：</h4>
                <textarea class="solution-steps" rows="2" placeholder="解决步骤"></textarea>
                <textarea class="solution-code" rows="3" placeholder="关键代码/配置（如有）"></textarea>
                <textarea class="solution-notes" rows="1" placeholder="注意事项"></textarea>
            `;
            this.solutionsContainer.appendChild(solutionItem);
        });
        
        // 模板按钮
        this.templateBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const templateType = btn.dataset.template;
                this.applyTemplate(templateType);
            });
        });
        
        // 选项卡切换
        this.tabBtns.forEach(btn => {
            btn.addEventListener('click', () => {
                const tabId = btn.dataset.tab;
                this.switchTab(tabId);
            });
        });
        
        // 设置模态框事件
        this.closeModal.addEventListener('click', () => this.closeSettings());
        this.saveSettingsBtn.addEventListener('click', () => this.saveSettingsFromUI());
        this.cancelSettingsBtn.addEventListener('click', () => this.closeSettings());
        
        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            if (e.target === this.settingsModal) {
                this.closeSettings();
            }
        });
    }

    // 渲染记录列表
    renderLogList() {
        this.logList.innerHTML = '';
        
        if (this.logs.length === 0) {
            this.logList.innerHTML = '<div class="no-logs">暂无记录，请点击上方"新建记录"按钮创建</div>';
            return;
        }
        
        // 按日期倒序排序
        const sortedLogs = [...this.logs].sort((a, b) => 
            new Date(b.date) - new Date(a.date)
        );
        
        sortedLogs.forEach(log => {
            const logItem = document.createElement('div');
            logItem.className = `log-item ${this.currentLogId === log.id ? 'active' : ''}`;
            logItem.innerHTML = `
                <h4>${log.title}</h4>
                <p>${log.date}</p>
            `;
            logItem.addEventListener('click', () => this.loadLog(log.id));
            this.logList.appendChild(logItem);
        });
    }

    // 创建新记录
    createNewLog() {
        // 清空编辑器
        this.clearEditor();
        
        // 重置当前记录ID
        this.currentLogId = null;
        
        // 重新渲染记录列表
        this.renderLogList();
        
        // 聚焦到标题输入框
        this.logTitle.focus();
    }

    // 加载记录
    loadLog(logId) {
        const log = this.logs.find(log => log.id === logId);
        if (!log) return;
        
        // 更新当前记录ID
        this.currentLogId = logId;
        
        // 填充编辑器
        this.logTitle.value = log.title;
        this.logDate.value = log.date;
        this.todayTasks.value = log.todayTasks || '';
        this.learnings.value = log.learnings || '';
        this.tomorrowPlan.value = log.tomorrowPlan || '';
        
        // 填充问题
        this.problemsContainer.innerHTML = '';
        if (log.problems && log.problems.length > 0) {
            log.problems.forEach((problem, index) => {
                const problemItem = document.createElement('div');
                problemItem.className = 'problem-item';
                problemItem.innerHTML = `
                    <h4>问题${index + 1}：</h4>
                    <textarea class="problem-description" rows="2" placeholder="问题描述">${problem.description || ''}</textarea>
                    <textarea class="problem-scene" rows="1" placeholder="出现场景">${problem.scene || ''}</textarea>
                    <textarea class="problem-scope" rows="1" placeholder="影响范围">${problem.scope || ''}</textarea>
                    <textarea class="problem-methods" rows="1" placeholder="尝试过的方法">${problem.methods || ''}</textarea>
                    <textarea class="problem-error" rows="1" placeholder="错误信息（如有）">${problem.error || ''}</textarea>
                `;
                this.problemsContainer.appendChild(problemItem);
            });
        } else {
            // 添加一个空问题
            this.addProblemBtn.click();
        }
        
        // 填充解决方案
        this.solutionsContainer.innerHTML = '';
        if (log.solutions && log.solutions.length > 0) {
            log.solutions.forEach((solution, index) => {
                const solutionItem = document.createElement('div');
                solutionItem.className = 'solution-item';
                solutionItem.innerHTML = `
                    <h4>解决方案${index + 1}：</h4>
                    <textarea class="solution-steps" rows="2" placeholder="解决步骤">${solution.steps || ''}</textarea>
                    <textarea class="solution-code" rows="3" placeholder="关键代码/配置（如有）">${solution.code || ''}</textarea>
                    <textarea class="solution-notes" rows="1" placeholder="注意事项">${solution.notes || ''}</textarea>
                `;
                this.solutionsContainer.appendChild(solutionItem);
            });
        } else {
            // 添加一个空解决方案
            this.addSolutionBtn.click();
        }
        
        // 重新渲染记录列表
        this.renderLogList();
    }

    // 保存当前记录
    saveCurrentLog() {
        // 获取表单数据
        const title = this.logTitle.value.trim();
        const date = this.logDate.value;
        
        // 验证必填字段
        if (!title) {
            alert('请输入记录标题');
            this.logTitle.focus();
            return;
        }
        
        if (!date) {
            alert('请选择日期');
            this.logDate.focus();
            return;
        }
        
        // 获取问题数据
        const problemItems = this.problemsContainer.querySelectorAll('.problem-item');
        const problems = Array.from(problemItems).map(item => ({
            description: item.querySelector('.problem-description').value.trim(),
            scene: item.querySelector('.problem-scene').value.trim(),
            scope: item.querySelector('.problem-scope').value.trim(),
            methods: item.querySelector('.problem-methods').value.trim(),
            error: item.querySelector('.problem-error').value.trim()
        })).filter(problem => Object.values(problem).some(value => value));
        
        // 获取解决方案数据
        const solutionItems = this.solutionsContainer.querySelectorAll('.solution-item');
        const solutions = Array.from(solutionItems).map(item => ({
            steps: item.querySelector('.solution-steps').value.trim(),
            code: item.querySelector('.solution-code').value.trim(),
            notes: item.querySelector('.solution-notes').value.trim()
        })).filter(solution => Object.values(solution).some(value => value));
        
        // 构建记录对象
        const logData = {
            title,
            date,
            todayTasks: this.todayTasks.value.trim(),
            problems,
            solutions,
            learnings: this.learnings.value.trim(),
            tomorrowPlan: this.tomorrowPlan.value.trim(),
            lastModified: new Date().toISOString()
        };
        
        if (this.currentLogId) {
            // 更新现有记录
            const index = this.logs.findIndex(log => log.id === this.currentLogId);
            if (index !== -1) {
                this.logs[index] = { ...this.logs[index], ...logData };
            }
        } else {
            // 创建新记录
            const newLog = {
                id: Date.now().toString(), // 使用时间戳作为唯一ID
                ...logData
            };
            this.logs.push(newLog);
            this.currentLogId = newLog.id;
        }
        
        // 保存到localStorage
        this.saveLogs();
        
        // 重新渲染记录列表
        this.renderLogList();
        
        // 更新预览
        if (this.tabBtns[1].classList.contains('active')) {
            this.renderPreview();
        }
        
        // 显示保存成功提示
        alert('记录已保存');
    }

    // 删除当前记录
    deleteCurrentLog() {
        if (!this.currentLogId) {
            alert('没有可删除的记录');
            return;
        }
        
        if (confirm('确定要删除这条记录吗？')) {
            // 从数组中移除记录
            this.logs = this.logs.filter(log => log.id !== this.currentLogId);
            
            // 保存到localStorage
            this.saveLogs();
            
            // 清空编辑器
            this.clearEditor();
            
            // 重置当前记录ID
            this.currentLogId = null;
            
            // 重新渲染记录列表
            this.renderLogList();
        }
    }

    // 清空编辑器
    clearEditor() {
        // 设置默认标题和日期
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        
        this.logTitle.value = `${formattedDate} 日常记录`;
        this.logDate.value = formattedDate;
        this.todayTasks.value = '';
        this.learnings.value = '';
        this.tomorrowPlan.value = '';
        
        // 清空问题和解决方案
        this.problemsContainer.innerHTML = '';
        this.solutionsContainer.innerHTML = '';
        
        // 添加一个空问题和解决方案
        this.addProblemBtn.click();
        this.addSolutionBtn.click();
        
        // 清空预览
        this.previewTitle.textContent = '预览';
        this.previewContent.innerHTML = '<p>请先填写内容并点击保存，然后切换到预览视图。</p>';
    }

    // 应用模板
    applyTemplate(templateType) {
        // 清空当前内容
        this.clearEditor();
        
        // 重置当前记录ID
        this.currentLogId = null;
        
        // 根据模板类型设置内容
        const today = new Date();
        const formattedDate = today.toISOString().split('T')[0];
        
        switch (templateType) {
            case 'daily':
                this.logTitle.value = `${formattedDate} 日常记录`;
                this.todayTasks.value = `- [ ] 任务1
- [ ] 任务2
- [ ] 任务3`;
                this.tomorrowPlan.value = `- [ ] 任务1
- [ ] 任务2
- [ ] 任务3`;
                break;
            case 'problem':
                this.logTitle.value = `${formattedDate} 问题解决方案记录`;
                // 已经添加了空的问题和解决方案表单
                break;
            case 'project':
                this.logTitle.value = `${formattedDate} 项目总结`;
                this.todayTasks.value = `- [ ] 总结项目成果
- [ ] 分析遇到的问题
- [ ] 提炼经验教训`;
                this.learnings.value = `- 项目成功经验
- 需要改进的地方`;
                break;
        }
        
        // 重新渲染记录列表
        this.renderLogList();
        
        // 聚焦到标题输入框
        this.logTitle.focus();
    }

    // 切换选项卡
    switchTab(tabId) {
        // 切换按钮状态
        this.tabBtns.forEach(btn => {
            btn.classList.remove('active');
            if (btn.dataset.tab === tabId) {
                btn.classList.add('active');
            }
        });
        
        // 切换内容面板
        this.tabPanes.forEach(pane => {
            pane.classList.remove('active');
            if (pane.id === `${tabId}-pane`) {
                pane.classList.add('active');
            }
        });
        
        // 如果切换到预览视图，渲染预览
        if (tabId === 'preview') {
            this.renderPreview();
        }
    }

    // 渲染预览
    renderPreview() {
        if (!this.currentLogId) {
            this.previewTitle.textContent = '预览';
            this.previewContent.innerHTML = '<p>请先填写内容并点击保存，然后切换到预览视图。</p>';
            return;
        }
        
        const log = this.logs.find(log => log.id === this.currentLogId);
        if (!log) return;
        
        // 设置预览标题
        this.previewTitle.textContent = log.title;
        
        // 构建预览内容
        let previewHtml = `
            <h3>日期：${log.date}</h3>
        `;
        
        if (log.todayTasks) {
            previewHtml += `
                <h3>今日工作内容</h3>
                <ul>${this.convertTextToList(log.todayTasks)}</ul>
            `;
        }
        
        if (log.problems && log.problems.length > 0) {
            previewHtml += '<h3>遇到的问题</h3>';
            log.problems.forEach((problem, index) => {
                if (problem.description) {
                    previewHtml += `
                        <h4>问题${index + 1}：${problem.description}</h4>
                        <ul>
                            ${problem.scene ? `<li><strong>出现场景</strong>：${problem.scene}</li>` : ''}
                            ${problem.scope ? `<li><strong>影响范围</strong>：${problem.scope}</li>` : ''}
                            ${problem.methods ? `<li><strong>尝试过的方法</strong>：${problem.methods}</li>` : ''}
                            ${problem.error ? `<li><strong>错误信息</strong>：${problem.error}</li>` : ''}
                        </ul>
                    `;
                }
            });
        }
        
        if (log.solutions && log.solutions.length > 0) {
            previewHtml += '<h3>解决方案</h3>';
            log.solutions.forEach((solution, index) => {
                previewHtml += `<h4>解决方案${index + 1}：</h4>`;
                if (solution.steps) {
                    previewHtml += `
                        <h5>解决步骤</h5>
                        <ul>${this.convertTextToList(solution.steps)}</ul>
                    `;
                }
                if (solution.code) {
                    previewHtml += `
                        <h5>关键代码/配置</h5>
                        <pre><code>${solution.code}</code></pre>
                    `;
                }
                if (solution.notes) {
                    previewHtml += `
                        <h5>注意事项</h5>
                        <p>${solution.notes}</p>
                    `;
                }
            });
        }
        
        if (log.learnings) {
            previewHtml += `
                <h3>学习与收获</h3>
                <ul>${this.convertTextToList(log.learnings)}</ul>
            `;
        }
        
        if (log.tomorrowPlan) {
            previewHtml += `
                <h3>明日计划</h3>
                <ul>${this.convertTextToList(log.tomorrowPlan)}</ul>
            `;
        }
        
        // 设置预览内容
        this.previewContent.innerHTML = previewHtml;
    }

    // 将文本转换为列表HTML
    convertTextToList(text) {
        if (!text) return '';
        
        const lines = text.split('\n');
        let listHtml = '';
        
        lines.forEach(line => {
            line = line.trim();
            if (line) {
                // 移除列表标记（如：- [ ]、-、1. 等）
                const cleanText = line.replace(/^[-\d.]+\s*\[?\s*\]?\s*/, '');
                listHtml += `<li>${cleanText}</li>`;
            }
        });
        
        return listHtml;
    }

    // 搜索记录
    searchLogs() {
        const searchTerm = this.searchInput.value.toLowerCase().trim();
        
        if (!searchTerm) {
            this.renderLogList();
            return;
        }
        
        const filteredLogs = this.logs.filter(log => 
            log.title.toLowerCase().includes(searchTerm) ||
            log.date.includes(searchTerm) ||
            (log.todayTasks && log.todayTasks.toLowerCase().includes(searchTerm)) ||
            (log.learnings && log.learnings.toLowerCase().includes(searchTerm))
        );
        
        this.logList.innerHTML = '';
        
        if (filteredLogs.length === 0) {
            this.logList.innerHTML = '<div class="no-logs">没有找到匹配的记录</div>';
            return;
        }
        
        // 按日期倒序排序
        const sortedLogs = [...filteredLogs].sort((a, b) => 
            new Date(b.date) - new Date(a.date)
        );
        
        sortedLogs.forEach(log => {
            const logItem = document.createElement('div');
            logItem.className = `log-item ${this.currentLogId === log.id ? 'active' : ''}`;
            logItem.innerHTML = `
                <h4>${log.title}</h4>
                <p>${log.date}</p>
            `;
            logItem.addEventListener('click', () => this.loadLog(log.id));
            this.logList.appendChild(logItem);
        });
    }

    // 导出数据
    exportData() {
        if (this.logs.length === 0) {
            alert('没有可导出的数据');
            return;
        }
        
        // 转换为JSON字符串
        const jsonData = JSON.stringify(this.logs, null, 2);
        
        // 创建Blob对象
        const blob = new Blob([jsonData], { type: 'application/json' });
        
        // 创建下载链接
        const url = URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = `work_logs_${new Date().toISOString().split('T')[0]}.json`;
        
        // 触发下载
        document.body.appendChild(a);
        a.click();
        
        // 清理
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
    }

    // 打开设置
    openSettings() {
        // 填充设置表单
        this.themeSelect.value = this.settings.theme;
        this.autoSave.checked = this.settings.autoSave;
        this.saveInterval.value = this.settings.saveInterval;
        
        // 显示设置模态框
        this.settingsModal.style.display = 'flex';
    }

    // 关闭设置
    closeSettings() {
        this.settingsModal.style.display = 'none';
    }

    // 从UI保存设置
    saveSettingsFromUI() {
        this.settings.theme = this.themeSelect.value;
        this.settings.autoSave = this.autoSave.checked;
        this.settings.saveInterval = parseInt(this.saveInterval.value) || 30;
        
        // 保存设置
        this.saveSettings();
        
        // 关闭模态框
        this.closeSettings();
        
        // 显示保存成功提示
        alert('设置已保存');
    }
}

// 当页面加载完成后初始化应用
document.addEventListener('DOMContentLoaded', () => {
    const app = new WorkLogSystem();
});